<script>
import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "TimeSelect",
  props: {
    timedata: {
      type: Array,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      containerHeight: 0,
      containerWidth: 0,
      timeZoneList: [],
      scale: 0,
      isFirstClick: false,
      firstClickIndex: null,
      firstClickX: 0,
    });

    const refContainer = ref(null);

    const initialWeekName = (e) => {
      let str = "";
      switch (e) {
        case 0:
          str = "一";
          break;
        case 1:
          str = "二";
          break;
        case 2:
          str = "三";
          break;
        case 3:
          str = "四";
          break;
        case 4:
          str = "五";
          break;
        case 5:
          str = "六";
          break;
        case 6:
          str = "日";
          break;
      }
      return `星期${str}`;
    };

    watch(
      () => props.timedata,
      (a) => {
        state.timeZoneList = a;
        if (state.timeZoneList.length === 1) {
          initTimeZoneList();
        }
      }
    );

    const initTimeZoneList = () => {
      state.timeZoneList = [
        {
          timeList: [],
          // targetTracking: [],
          week: 1,
        },
        {
          timeList: [],
          // targetTracking: [],
          week: 2,
        },
        {
          timeList: [],
          // targetTracking: [],
          week: 3,
        },
        {
          timeList: [],
          // targetTracking: [],
          week: 4,
        },
        {
          timeList: [],
          // targetTracking: [],
          week: 5,
        },
        {
          timeList: [],
          // targetTracking: [],
          week: 6,
        },
        {
          // 定时任务列表
          timeList: [],
          // 目标跟踪列表
          // targetTracking: [],
          week: 7,
        },
      ];
    };

    const calcHour = (e) => {
      let refProgressBoxWidth = 0;
      if (refContainer.value) {
        refProgressBoxWidth = refContainer.value.clientWidth - 84;
      }
      const timezone = (e / refProgressBoxWidth) * 1440;
      const str = (timezone / 60).toString();
      if (str.indexOf(".") !== -1) {
        const tempList = str.split(".");
        return parseInt(tempList[0]);
      } else {
        return parseInt(str);
      }
    };

    const calcMinutes = (e) => {
      let refProgressBoxWidth = 0;
      if (refContainer.value) {
        refProgressBoxWidth = refContainer.value.clientWidth - 84;
      }
      const timezone = (e / refProgressBoxWidth) * 1440;
      const str = (timezone % 60).toString();
      if (str.indexOf(".") !== -1) {
        const tempList = str.split(".");
        return parseInt(tempList[0]);
      } else {
        return parseInt(str);
      }
    };

    const clearDotLast = (e) => {
      const str = e.toString();
      if (str.indexOf(".") !== -1) {
        const tempList = str.split(".");
        return parseInt(tempList[0]);
      } else {
        return parseInt(str);
      }
    };

    onMounted(() => {
      nextTick(() => {
        if (refContainer.value) {
          state.containerHeight = refContainer.value.clientHeight;
          state.containerWidth = refContainer.value.clientWidth - 69;
        }
      });
      initTimeZoneList();
      state.scale = window.devicePixelRatio;

      state.timeZoneList = props.timedata;
    });

    const handleTimeZoneItemClick = (e, index) => {
      // 鼠标点击的位置相对于进度条的哪里
      const currentLeft = e["offsetX"];
      if (!state.isFirstClick) {
        state.isFirstClick = true;
        state.firstClickX = currentLeft + 2;
        state.firstClickIndex = index;
      } else {
        if (index !== state.firstClickIndex) {
          ElMessage.warning(`请选中${initialWeekName(state.firstClickIndex)}`);
          return;
        }
        let startHour = null;
        let startMinutes = null;
        let endHour = null;
        let endMinutes = null;

        if (state.firstClickX === currentLeft) {
          ElMessage.warning("两次选中时间不能相同");
        } else if (state.firstClickX > currentLeft) {
          const startValue = currentLeft;
          const endValue = state.firstClickX;
          startHour = calcHour(startValue);
          startMinutes = calcMinutes(startValue);
          endHour = calcHour(endValue);
          endMinutes = calcMinutes(endValue);
          console.log(endMinutes);
          // 拼接数据至对象中
          const obj = {
            startHour,
            startMinutes,
            endHour,
            endMinutes,
            left: startValue,
            width: endValue - startValue - 2,
            startTime: new Date("2024-08-01 " + startHour + ":" + startMinutes),
            endTime: new Date("2024-08-01 " + endHour + ":" + endMinutes),
          };
          // 这里需要判断一下是定时任务还是目标跟踪，在外边选择的时候，加一个状态，存储就行
          if (true) {
            // 这里就当是定时任务了
            state.timeZoneList[index]["timeList"].push(obj);
          }
          state.isFirstClick = false;
        } else {
          const startValue = state.firstClickX;
          const endValue = currentLeft;
          startHour = calcHour(startValue);
          startMinutes = calcMinutes(startValue);
          endHour = calcHour(endValue);
          endMinutes = calcMinutes(endValue);

          const obj = {
            startHour,
            startMinutes,
            endHour,
            endMinutes,
            left: startValue,
            width: endValue - startValue - 2,
            startTime: new Date("2024-08-01 " + startHour + ":" + startMinutes),
            endTime: new Date("2024-08-01 " + endHour + ":" + endMinutes),
          };
          if (true) {
            state.timeZoneList[index]["timeList"].push(obj);
          }
          state.isFirstClick = false;
        }
        emit("changeTime", state.timeZoneList);
      }
    };

    /**
     * 点击了弹出窗中保存或者删除
     * @param item 当前选中项
     * @param type 定时任务还是目标跟踪，targetTracking ： 目标跟踪、 timeList ： 定时任务
     * @param method 0 删除、 1 保存
     */
    const handleTimeZoneChange = (item, type, method, index) => {
      let refProgressBoxWidth = 0;
      if (refContainer.value) {
        refProgressBoxWidth = refContainer.value.clientWidth - 84;
      }
      if (method === 0) {
        // 删除操作，该请求接口就请求接口，然后把item在对应的list中删掉
        let arr = state.timeZoneList[index].timeList;

        arr = arr.filter((itemA) => {
          if (itemA.left !== item.left && itemA.width !== item.width) {
            return item;
          }
        });
        state.timeZoneList[index].timeList = arr;
        emit("changeTime", state.timeZoneList);
      } else if (method === 1) {
        checkTime(item);

        const start = item["startHour"] * 60 + item["startMinutes"] * 1;
        const end = item["endHour"] * 60 + item["endMinutes"] * 1;

        const startValue = (start / 1440) * refProgressBoxWidth;
        // const endValue = (end / 1440) * refProgressBoxWidth;
        const endValue = (end / 1440) * refProgressBoxWidth + 2;

        item["left"] = clearDotLast(startValue);
        item["width"] = clearDotLast(endValue - startValue);
        emit("changeTime", state.timeZoneList);
      }
    };

    const checkTime = (item) => {
      if (item["startHour"] > 24) {
        item["startHour"] = 24;
      } else if (item["startHour"] < 0) {
        item["startHour"] = 0;
      } else if (item["startHour"] === 24) {
        item["startMinutes"] = 0;
      }

      if (item["endHour"] > 24) {
        item["endHour"] = 24;
        item["endMinutes"] = 0;
      } else if (item["endHour"] < 0) {
        item["endHour"] = 0;
      } else if (item["endHour"] === 24) {
        item["endMinutes"] = 0;
      }

      if (item["startMinutes"] > 60) {
        item["startMinutes"] = 59;
      } else if (item["startMinutes"] < 0) {
        item["startMinutes"] = 0;
      }

      if (item["endMinutes"] > 60) {
        item["endMinutes"] = 59;
      } else if (item["endMinutes"] < 0) {
        item["endMinutes"] = 0;
      }
    };

    return {
      ...toRefs(state),
      refContainer,
      initialWeekName,
      handleTimeZoneItemClick,
      handleTimeZoneChange,
    };
  },
});
</script>

<template>
  <div ref="refContainer" class="component-time-select-container">
    <div
      v-for="(item, index1) in timeZoneList"
      :key="index1"
      :style="{ height: (containerHeight - 12 * 6) / 7 + 'px' }"
      class="time-select-line"
    >
      <div class="time-zone-label">{{ initialWeekName(index1) }}</div>
      <div
        class="time-zone-progress-bound"
        @click="(e) => handleTimeZoneItemClick(e, index1)"
      >
        <!--        0-24的数字，奇数不显示-->
        <div class="num-hour-bound">
          <div
            class="num-hour"
            v-for="(item, index) in 24"
            :key="index"
            :style="{
              width: (containerWidth - 24) / 24 + 1 * scale + 'px',
            }"
          >
            <div class="num-word">{{ index % 2 === 0 ? index : "" }}</div>
          </div>
          <div class="num-hour">
            <div class="num-word">24</div>
          </div>
        </div>
        <!--        中部小竖线 25条小竖线，每条距左 width / 24 第一条小竖线清除居左 -->
        <div class="sub-line-bound">
          <div
            class="sub-line"
            v-for="(item, index) in 25"
            :key="index"
            :style="{
              marginRight: (containerWidth - 13) / 25 + 'px',
              borderLeftWidth: 1 * scale + 'px',
            }"
          />
        </div>
        <!--        底部进度条-->
        <div ref="refProgressBox" class="time-zone-progress-box">
          <el-popover
            placement="top"
            :width="240"
            trigger="click"
            v-for="(item, index) in item['targetTracking']"
            :key="'targetTracking_' + index"
          >
            <template #reference>
              <div
                class="target-tracking"
                :style="{
                  left: item['left'] + 'px',
                  width: item['width'] + 'px',
                }"
                @click.stop
              />
            </template>
            <div class="time-block">
              <el-row :gutter="8">
                <el-col :span="5">
                  <el-input v-model="item['startHour']" />
                </el-col>
                <el-col :span="1">
                  <div style="height: 100%; display: flex; align-items: center">
                    :
                  </div>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="item['startMinutes']" />
                </el-col>
                <el-col :span="5">
                  <el-input v-model="item['endHour']" />
                </el-col>
                <el-col :span="1">
                  <div style="height: 100%; display: flex; align-items: center">
                    :
                  </div>
                </el-col>
                <el-col :span="6">
                  <el-input v-model="item['endMinutes']" />
                </el-col>
              </el-row>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <el-button
                  link
                  type="primary"
                  @click="handleTimeZoneChange(item, 'targetTracking', 0)"
                  >删除</el-button
                >
                <el-button
                  link
                  type="primary"
                  @click="handleTimeZoneChange(item, 'targetTracking', 1)"
                  >保存</el-button
                >
              </div>
            </div>
          </el-popover>
          <el-popover
            placement="top"
            :width="240"
            trigger="click"
            v-for="(item, index) in item['timeList']"
            :key="'scheduledTasks_' + index"
          >
            <template #reference>
              <div
                class="scheduled-task"
                :style="{
                  left: item['left'] + 'px',
                  width: item['width'] + 'px',
                }"
                @click.stop
              />
            </template>
            <div class="time-block">
              <el-row :gutter="8">
                <el-col :span="5">
                  <el-input min="0" v-model.number="item['startHour']" />
                </el-col>
                <el-col :span="1">
                  <div style="height: 100%; display: flex; align-items: center">
                    :
                  </div>
                </el-col>
                <el-col :span="6">
                  <el-input max="60" v-model.number="item['startMinutes']" />
                </el-col>
                <el-col :span="5">
                  <el-input max="24" v-model.number="item['endHour']" />
                </el-col>
                <el-col :span="1">
                  <div style="height: 100%; display: flex; align-items: center">
                    :
                  </div>
                </el-col>
                <el-col :span="6">
                  <el-input max="60" v-model.number="item['endMinutes']" />
                </el-col>
              </el-row>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <el-button
                  link
                  type="primary"
                  @click="handleTimeZoneChange(item, 'timeList', 0, index1)"
                  >删除</el-button
                >
                <el-button
                  link
                  type="primary"
                  @click="handleTimeZoneChange(item, 'timeList', 1)"
                  >保存</el-button
                >
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.component-time-select-container {
  height: 100%;
  padding-right: 12px;

  .time-select-line {
    margin-top: 12px;
    display: flex;
    align-items: center;

    &:first-child {
      margin-top: 0;
    }

    .time-zone-label {
      width: 72px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .time-zone-progress-bound {
      width: calc(100% - 70px);
      height: 100%;
      cursor: pointer;

      .num-hour-bound {
        height: 50%;
        width: 100%;
        display: flex;

        .num-hour {
          height: 100%;
          font-size: 12px;
          position: relative;

          .num-word {
            position: absolute;
            left: 0;
            transform: translateX(-50%);
            color: #b9b9b9;
            user-select: none;
          }

          &:last-child {
            width: 0;
          }
        }
      }

      .sub-line-bound {
        height: 20%;
        width: 100%;
        display: flex;

        .sub-line {
          border-left-style: solid;
          border-left-color: #b9b9b9;
          box-sizing: border-box;
          height: 100%;

          &:last-child {
            margin-right: 0 !important;
          }
        }
      }

      .time-zone-progress-box {
        height: 30%;
        background-color: #ffffff;
        border: 1px solid #b9b9b9;
        position: relative;

        .target-tracking {
          height: 100%;
          position: absolute;
          background: #39b54a;
        }

        .scheduled-task {
          height: 100%;
          position: absolute;
          background: #1890ff;
        }
      }
    }
  }
}
</style>
